//
//  ViewController.m
//  AnalogOnlineChat
//
//  Created by admin on 2019/10/6.
//  Copyright © 2019 admin. All rights reserved.
//

#import "ViewController.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *IPLabel;
@property (weak, nonatomic) IBOutlet UISwitch *switchBtn;
@property (weak, nonatomic) IBOutlet UITextField *portLabel;
- (IBAction)switchAct:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *revcMessageLabel;
@property (weak, nonatomic) IBOutlet UITextField *sendMessageLabel;
- (IBAction)sendBtn:(id)sender;

@property(nonatomic,assign)int clientSocket;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.switchBtn setOn:NO];
}


- (IBAction)switchAct:(id)sender
{
    BOOL isComplete = NO;
    
    if ([self.IPLabel.text isEqualToString:@""] || [self.portLabel.text isEqualToString:@""])
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"IP地址或端口号不能为空，请确认输入。" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *comfirmAc = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                       //点击确定要执行的代码
                [self.switchBtn setOn:NO];
                   }];
           [alertVC addAction:comfirmAc];
           [self presentViewController:alertVC animated:YES completion:nil];
    }else{
        isComplete = YES;
    }
   
    if (isComplete)
    {
        BOOL isButtonOn = [self.switchBtn isOn];
        if (isButtonOn) {
        
            if ([self connectToIP:self.IPLabel.text AndPort:[self.portLabel.text intValue]])
            {
                [self tipWithMessage:@"成功连接"];
            }else{
                [self.switchBtn setOn:NO];
                [self tipWithMessage:@"失败连接"];
            }

        }else {
            close(self.clientSocket);
            [self tipWithMessage:@"断开连接"];
        }
    }
    
}


- (IBAction)sendBtn:(id)sender
{
    self.revcMessageLabel.text = [self sendAndRecv:self.sendMessageLabel.text];
}

- (NSString *)sendAndRecv:(NSString *)sendMsg
{
    const char *msg = sendMsg.UTF8String;
    ssize_t sendCount = send(self.clientSocket, msg, strlen(msg), 0);
    NSLog(@"发送的字符数 %zd",sendCount);
    
    
    //4. 接收服务器发送的消息
    //返回的是实际的字节个数
    uint8_t buffer[1024];
    ssize_t recvCount = recv(self.clientSocket, buffer, sizeof(buffer), 0);
    NSLog(@"接收的字节数 %zd",recvCount);
    
    //把字节数组转换为字符串
    NSData *data = [NSData dataWithBytes:buffer length:recvCount];
    NSString *recvMessage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return recvMessage;
}

- (BOOL)connectToIP:(NSString *)ip AndPort:(int)port
{
    //1. 创建Socket
    //返回值 如果创建成功返回Socket的描述符，失败-1
    int clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    self.clientSocket = clientSocket;
    
    //2. 连接服务器
    /*
     失败的原因，是12345端口没有被使用。
     连接服务器- 打开Netcat，模拟服务器。
        打开终端>_
            nc -lk 12345
        nc -> Netcat 终端下用于调试和检查网络的工具
     */
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(ip.UTF8String);
    //计算机存储数字的时候，存储的方式不一样，但是网络都是使用大尾顺序，使用htons可以根据计算机转换保证为大尾顺序
    //大尾顺序 - 地址的低位存储值的高位，小尾顺序 - 地址的低位存储值的低位。
    addr.sin_port = htons(port);
    
    int result = connect(clientSocket, (const struct sockaddr *) &addr, sizeof(addr));
    if (result != 0)
    {
        NSLog(@"失败");
        return NO;
    }
    
    return YES;
}

//提示弹窗

- (void)tipWithMessage:(NSString *)message
{

      UILabel * tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(UIScreen.mainScreen.bounds.size.width/2 - 60, UIScreen.mainScreen.bounds.size.height/2, 120, 30)];
      // 设置提示内容
      [tipLabel setText:message];
      tipLabel.backgroundColor = [UIColor blackColor];
      tipLabel.layer.cornerRadius = 5;
      tipLabel.layer.masksToBounds = YES;
      tipLabel.textAlignment = NSTextAlignmentCenter;
      tipLabel.textColor = [UIColor whiteColor];
      [self.view addSubview:tipLabel];
      // 设置时间和动画效果
      [UIView animateWithDuration:2.0 animations:^{
      tipLabel.alpha = 0.0;
      } completion:^(BOOL finished) {
      // 动画完毕从父视图移除
      [tipLabel removeFromSuperview];
      }];
    
}
 


@end
